package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.article.service.ArticleHomeService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.common.thread.ApThreadLocal;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
@Slf4j
public class ArticleHomeServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ArticleHomeService {

    @Autowired
    private ApArticleConfigMapper configMapper;
    @Autowired
    private ApArticleContentMapper contentMapper;

    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;

    //文章的列表展示
    @Override
    public ResponseResult load(ArticleHomeDto dto) {
        //因为前端有问题，建议大家每页显示5条，测试的时候就可以上拉和下拉
        List<ApArticle> list = baseMapper.loadArticleList(dto);
        return ResponseResult.okResult(list);
    }

    //保存文章数据
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        //try {
        //    TimeUnit.SECONDS.sleep(3);
        //} catch (InterruptedException e) {
        //    e.printStackTrace();
        //}


        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1 准备文章对象
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto, article);

        //2 判断文章id是否存在
        if (article.getId() == null) {
            //2.1 文章id不存在  新增  文章   文章配置    文章内容

            //新增文章
            this.save(article);

            //新增文章配置
            ApArticleConfig config = new ApArticleConfig();
            config.setArticleId(article.getId());
            config.setIsComment(true);//是否可以评论
            config.setIsForward(true);//是否可以转发
            config.setIsDelete(false);//是否删除
            config.setIsDown(false);  //是否下架
            //新增
            configMapper.insert(config);

            //新增文章内容
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(article.getId());
            content.setContent(dto.getContent());
            //新增
            contentMapper.insert(content);

        } else {
            //2.2 文章id存在   修改   文章    文章内容
            this.updateById(article);

            //查询文章内容数据
            ApArticleContent content = contentMapper.selectOne(Wrappers.lambdaQuery(ApArticleContent.class)
                    .eq(ApArticleContent::getArticleId, article.getId()));
            //修改文章内容
            content.setContent(dto.getContent());
            contentMapper.updateById(content);
        }

        //保存文章成功后，生成静态页，上传到MinIO中
        articleFreemarkerService.buildArticleToMinIO(article.getId(), dto.getContent());

        //3 返回结果 ， 文章id
        return ResponseResult.okResult(article.getId());
    }

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {

        //0.检查参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //{ "isfollow": true, "islike": true,"isunlike": false,"iscollection": true }
        boolean isfollow = false, islike = false, isunlike = false, iscollection = false;

        ApUser user = ApThreadLocal.getUser();
        if (user != null) {
            //喜欢行为
            String likeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (StringUtils.isNotBlank(likeBehaviorJson)) {
                islike = true;
            }
            //不喜欢的行为
            String unLikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId().toString(), user.getId().toString());
            if (StringUtils.isNotBlank(unLikeBehaviorJson)) {
                isunlike = true;
            }
            //是否收藏
            String collctionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getArticleId().toString());
            if (StringUtils.isNotBlank(collctionJson)) {
                iscollection = true;
            }

            //是否关注
            Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), dto.getAuthorId().toString());
            System.out.println(score);
            if (score != null) {
                isfollow = true;
            }

        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isfollow", isfollow);
        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("iscollection", iscollection);

        return ResponseResult.okResult(resultMap);
    }

    @Override
    public ResponseResult load2(ArticleHomeDto dto) {
        String json = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
        if (StringUtils.isNotBlank(json)) {
            List<HotArticleVo> vos = JSON.parseArray(json, HotArticleVo.class);
            return ResponseResult.okResult(vos);
        }

        return load(dto);
    }
}